﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace INSTA_ORM
{
    public class XmlUtil
    {
        public IList<ClassMapping> openXML()
        {
            IList<ClassMapping> classMappingData = new List<ClassMapping>();

            XDocument xmlDoc = XDocument.Load(ApplicationConstants.ConfigConstants.CONFIGFILE_NAME);

            var classMappings = from mappingObject in xmlDoc.Descendants("classMapping")
                                select mappingObject;


            foreach (var classMapping in classMappings)
            {
                ClassMapping classMappingInfo = null;
                // Creation de notre objet ClassMapping..
                classMappingInfo = new ClassMapping()
                {
                    ClassName = classMapping.Attribute("className").Value,
                    TableName = classMapping.Attribute("tableName").Value
                };


                // ajout des properties dans le dictionnaire de properties de l'objet classMappingInfos
                var propertyMappings = from property in classMapping.Descendants("property")
                                       select new PropertyMapping()
                                       {
                                           PropertyName = property.Attribute("propertyName").Value,
                                           PropertyFieldName = property.Attribute("propertyFieldName").Value,
                                           IsPrimaryKey = Convert.ToBoolean(property.Attribute("isPrimaryKey").Value)
                                       };


                foreach (var propertyMapping in propertyMappings)
                {

                    PropertyMapping property = new PropertyMapping()
                    {
                        PropertyName = propertyMapping.PropertyName,
                        PropertyFieldName = propertyMapping.PropertyFieldName,
                        IsPrimaryKey = propertyMapping.IsPrimaryKey
                    };

                    classMappingInfo.Properties.Add(property.PropertyName, property);

                }
                classMappingData.Add(classMappingInfo);

            }
            return classMappingData;
        }

        private void printClassMapping(ClassMapping info)
        {
            Console.WriteLine(info.TableName);
            Console.WriteLine(info.ClassName);

            foreach (var property in info.Properties.Values)
            {
                Console.WriteLine(property.PropertyName);
                Console.WriteLine(property.PropertyFieldName);
                Console.WriteLine(property.IsPrimaryKey);
            }
        }
    }
}